/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //1.假设A链表更长
        ListNode pLong = headA;
        ListNode pShort = headB;
        int lenA = 0;
        int lenB = 0;
        while (pLong != null) {
            lenA ++;
            pLong = pLong.next;
        }
        while (pShort != null) {
            lenB ++;
            pShort = pShort.next;
        }
        //遍历完数组后, pLong和pShort都为空, 需要重新赋值
        pLong = headA;
        pShort = headB;
        int len = lenA - lenB;
        //2.判断len是正数还是负数
        if (len < 0) { //len < 0 代表连表B更长
            pLong = headB;
            pShort = headA;
            len = lenB - lenA;
        }
        //上述两步走完之后, pLong一定指向长链表; pShort一定指向短链表
        //len一定是正数
        //3.让长链表的pLong走差值len步
        while (len != 0) {
            pLong = pLong.next;
            len--;
        }
        //一起走,直到相遇
        while (pLong != pShort) {
            pLong = pLong.next;
            pShort = pShort.next;
        }
        if (pLong == null && pShort == null) { // 如果两个引用最终都为空,证明连个链表不相交不相交.
            return null;
        }// 这段代码不写也能正确判断
        return pLong;
    }
}